﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;
using System.Configuration;

namespace C
{
    public class RoleController
    {
        public static void Insert(Role a)
        {
            HCDataContext db = new HCDataContext();
            if (GetByName(a.Name, db) != null) return;
            db.Roles.InsertOnSubmit(a);
            db.SubmitChanges();
        }

        public static void Update(Role a, HCDataContext db)
        {
            if (GetByName(a.Name, db) != null) return;
            db.SubmitChanges();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            Role a = db.Roles.Where(
                ik => ik.RoleID == id).First();

            if (!CanEdit(a.Name)) return;

            db.UserRoles.DeleteAllOnSubmit(a.UserRoles);
            db.TrangRoles.DeleteAllOnSubmit(a.TrangRoles);

            db.Roles.DeleteOnSubmit(a);
            db.SubmitChanges();
        }

        public static Role GetByID(int id, HCDataContext db)
        {
            return db.Roles.Where(
                ik => ik.RoleID == id).FirstOrDefault();
        }

        public static Role GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }

        public static Role GetByName(string name, HCDataContext db)
        {
            return db.Roles.Where(
                ik => ik.Name == name).FirstOrDefault();
        }

        public static bool CanEdit(string name)
        {
            if (name == GetAdminRoleName()) return false;
            if (name == GetUnregisterRoleName()) return false;
            if (name == GetRegisterRoleName()) return false;
            return true;
        }

        public static bool CanEdit(int id)
        {
            return CanEdit(GetByID(id).Name);
        }

        public static string GetAdminRoleName()
        {
            return ConfigurationManager.AppSettings["AdminRole"];
        }

        public static string GetUnregisterRoleName()
        {
            return ConfigurationManager.AppSettings["UnregisterRole"];
        }

        public static string GetRegisterRoleName()
        {
            return ConfigurationManager.AppSettings["RegisterRole"];
        }
    }
}